import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../config/env_config.dart';

class AIService {
  static final AIService _instance = AIService._internal();
  factory AIService() => _instance;
  AIService._internal();

  static const String _apiKeyPrefKey = 'aliyun_api_key';
  static const String _baseUrl = 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions';
  
  String? _apiKey;
  
  /// 初始化服务，优先使用环境配置中的API密钥，如果没有则从SharedPreferences加载
  Future<void> init() async {
    // 优先使用环境配置中的API密钥
    if (EnvConfig.useHardcodedApiKey()) {
      _apiKey = EnvConfig.aliyunApiKey;
      return;
    }
    
    // 如果没有环境配置，则从SharedPreferences加载
    final prefs = await SharedPreferences.getInstance();
    _apiKey = prefs.getString(_apiKeyPrefKey);
  }
  
  /// 检查是否已设置API密钥
  Future<bool> hasApiKey() async {
    // 如果内存中已有API密钥，直接返回true
    if (_apiKey != null && _apiKey!.isNotEmpty) return true;
    
    // 检查环境配置中是否有API密钥
    if (EnvConfig.useHardcodedApiKey()) {
      _apiKey = EnvConfig.aliyunApiKey;
      return true;
    }
    
    // 如果环境配置中没有，则从SharedPreferences加载
    final prefs = await SharedPreferences.getInstance();
    _apiKey = prefs.getString(_apiKeyPrefKey);
    return _apiKey != null && _apiKey!.isNotEmpty;
  }
  
  /// 保存API密钥
  Future<void> saveApiKey(String apiKey) async {
    _apiKey = apiKey;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_apiKeyPrefKey, apiKey);
  }
  
  /// 清除API密钥
  Future<void> clearApiKey() async {
    _apiKey = null;
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(_apiKeyPrefKey);
  }
  
  /// 获取单词解析（含义和例句）
  Future<Map<String, String>> getWordExplanation(String word) async {
    // 确保API密钥已设置，优先使用环境配置中的API密钥
    if (EnvConfig.useHardcodedApiKey()) {
      _apiKey = EnvConfig.aliyunApiKey;
    }
    
    if (_apiKey == null || _apiKey!.isEmpty) {
      throw Exception('未设置阿里云API密钥');
    }
    
    try {
      final response = await http.post(
        Uri.parse(_baseUrl),
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ${_apiKey ?? ""}',
          'X-DashScope-Api-Key': _apiKey ?? "",
        },
        body: jsonEncode({
          'model': 'qwen-plus',
          'messages': [
            {
              'role': 'system',
              'content': '你是一个专业的英语教师，擅长解释英语单词的含义并提供例句。请提供简洁明了的解释和自然的例句。'
            },
            {
              'role': 'user',
              'content': '请解释单词"$word"的含义，并提供2个例句。格式为JSON，包含meaning和examples两个字段，examples是一个数组。'
            }
          ],
          'temperature': 0.7,
        }),
      );
      
      if (response.statusCode == 200) {
        final data = jsonDecode(response.body);
        final content = data['choices'][0]['message']['content'];
        
        // 尝试解析返回的JSON内容
        try {
          final parsedContent = jsonDecode(content);
          return {
            'meaning': parsedContent['meaning'] ?? '',
            'examples': (parsedContent['examples'] as List).map((example) => '• $example').join('\n\n'),
          };
        } catch (e) {
          // 如果无法解析JSON，则尝试从文本中提取信息
          final meaningMatch = RegExp(r'含义[:：]\s*(.+?)(?=\n|例句|$)').firstMatch(content);
          final examplesMatches = RegExp(r'例句\s*\d+[:：]\s*(.+?)(?=\n|例句|$)').allMatches(content);
          
          final meaning = meaningMatch?.group(1)?.trim() ?? '';
          final examples = examplesMatches
              .map((m) => '• ${m.group(1)?.trim() ?? ''}')
              .where((e) => e.length > 2) // 确保有内容（不只是'• '）
              .join('\n\n');
          
          // 如果正则表达式没有匹配到内容，尝试格式化原始内容
          if (meaning.isEmpty && examples.isEmpty) {
            // 检查内容是否包含JSON格式的文本
            if (content.contains('```json') && content.contains('```')) {
              // 提取JSON部分
              final jsonMatch = RegExp(r'```json\s*(.+?)\s*```', dotAll: true).firstMatch(content);
              if (jsonMatch != null) {
                try {
                  final jsonContent = jsonMatch.group(1)!;
                  final parsedJson = jsonDecode(jsonContent);
                  return {
                    'meaning': parsedJson['meaning'] ?? '',
                    'examples': (parsedJson['examples'] as List).map((example) => '• $example').join('\n\n'),
                  };
                } catch (_) {
                  // JSON解析失败，返回格式化的原始内容
                }
              }
            }
            
            // 移除Markdown代码块标记
            String cleanedContent = content
                .replaceAll('```json', '')
                .replaceAll('```', '')
                .trim();
                
            return {
              'meaning': cleanedContent,
              'examples': '',
            };
          }
          
          return {
            'meaning': meaning,
            'examples': examples,
          };
        }
      } else {
        throw Exception('API请求失败: ${response.statusCode} ${response.body}');
      }
    } catch (e) {
      throw Exception('获取单词解析失败: $e');
    }
  }
  
  /// 显示API密钥设置对话框
  static Future<bool> showApiKeyDialog(BuildContext context) async {
    final service = AIService();
    await service.init();
    
    // 检查是否使用环境配置中的API密钥
    if (EnvConfig.useHardcodedApiKey()) {
      // 如果使用环境配置中的API密钥，显示提示信息并返回true
      return await showDialog<bool>(
        context: context,
        builder: (context) => AlertDialog(
          title: const Text('API密钥已配置', style: TextStyle(fontFamily: 'FangSong')),
          content: const Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                '应用已通过代码配置了API密钥，无需手动设置。',
                style: TextStyle(fontFamily: 'FangSong'),
              ),
              SizedBox(height: 8),
              Text(
                '如需修改，请联系开发人员更新环境配置。',
                style: TextStyle(fontFamily: 'FangSong'),
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(true),
              child: Text('确定', style: TextStyle(fontFamily: 'FangSong')),
            ),
          ],
        ),
      ) ?? true;
    }
    
    // 如果没有使用环境配置中的API密钥，显示输入对话框
    final TextEditingController keyController = TextEditingController();
    keyController.text = service._apiKey ?? '';
    
    return await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('设置阿里云API密钥', style: TextStyle(fontFamily: 'FangSong')),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text(
              '请输入您的阿里云API密钥，用于获取单词解析功能。您可以在阿里云控制台获取API密钥。',
              style: TextStyle(fontFamily: 'FangSong'),
            ),
            const SizedBox(height: 16),
            TextField(
              controller: keyController,
              decoration: const InputDecoration(
                labelText: 'API Key',
                hintText: '阿里云API Key',
                border: OutlineInputBorder(),
              ),
              obscureText: true,
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: const Text('取消', style: TextStyle(fontFamily: 'FangSong')),
          ),
          TextButton(
            onPressed: () async {
              final apiKey = keyController.text.trim();
              if (apiKey.isNotEmpty) {
                await service.saveApiKey(apiKey);
                Navigator.of(context).pop(true);
              } else {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('API密钥不能为空', style: TextStyle(fontFamily: 'FangSong'))),
                );
              }
            },
            child: const Text('保存', style: TextStyle(fontFamily: 'FangSong')),
          ),
        ],
      ),
    ) ?? false;
  }
}